package com.eve.util.spring;

import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.StringTemplateSource;
import com.github.jknack.handlebars.io.TemplateSource;
import com.github.jknack.handlebars.springmvc.SpringTemplateLoader;
import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Handlebar模板工具
 * <p> 适用于后台服务，根据模板定制数据
 * @author: ivan.yao<haif.yao@gmail.com>
 * @date: 16/7/11.
 */
public class HandlebarTemplates implements ApplicationContextAware {

    private SpringTemplateLoader loader;

    /**
     * 编译并应用数据
     * <p> 1.模板根目录classpath:/templates
     * <p> 2.模板后缀名固定为.hbs
     * @param location	相对跟目录的文件名路径，不包括后缀名
     * @param params	上下文参数
     * @return
     */
    public String compileAndApply(String location, Object params) {
        try {
            Handlebars handlebars = new Handlebars(loader);
            Template template = handlebars.compile(location);
            return template.apply(params);
        } catch (Exception e) {
            return "";
        }
    }


    public String compileHbsContentAndApply(String content, Object params) {
        try {
            Handlebars handlebars = new Handlebars(loader);
            HashFunction hf = Hashing.sha1();
            HashCode hc = hf.newHasher().putString(content, Charsets.UTF_8).hash();
            TemplateSource templateSource = new StringTemplateSource(hc.toString(),content);
            Template template = handlebars.compile(templateSource);
            return template.apply(params);
        } catch (Exception e) {
            return "";
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        loader = new SpringTemplateLoader(context);
        loader.setPrefix("classpath:/templates");
        loader.setSuffix(".hbs");
    }
}
